#include <opencv2/opencv.hpp>
#include <string>
#include <vector>

// aaaaaaaaaaaaaaa

int main()
{
    std::string base_path = "/home/yu/Pictures";
    std::string a2z = base_path + "/aaa.png";

    int white_thre = 85;
    cv::Mat img = cv::imread(a2z, cv::IMREAD_GRAYSCALE);
    cv::threshold(img, img, white_thre, 255, cv::THRESH_BINARY);

    // cv::imshow("threshold", img);
    // cv::waitKey(0);

    std::vector<int> projection(img.cols, 0);
    for (int x = 0; x < img.cols; x++)
    {
        for (int y = 0; y < img.rows; y++)
        {
            if (img.at<uchar>(y, x) > 0)
                projection[x]++;
        }
    }

    // 找间隙（像素列几乎为 0 的地方）
    std::vector<cv::Rect> chars;

    bool inChar = false;
    int start = 0;
    for (int x = 0; x < img.cols; x++)
    {
        if (!inChar && projection[x] > 0)
        {
            start = x;
            inChar = true;
        }
        else if (inChar && projection[x] == 0)
        {
            chars.push_back(cv::Rect(start, 0, x - start, img.rows));
            inChar = false;
        }
    }

    std::cout << "rect.size is " << chars.size() << std::endl;

    for (auto t : chars)
    {
        std::cout << t.width << " ";
    }

    std::cout << std::endl;

    cv::Mat color;
    cvtColor(img, color, cv::COLOR_GRAY2BGR);
    for (auto &r : chars)
    {
        if (r.width < 6)
            rectangle(color, r, cv::Scalar(0, 255, 0), 1);
    }

    cv::imshow("segmentation", color);

    cv::Mat color2;
    cvtColor(img, color2, cv::COLOR_GRAY2BGR);
    for (auto &r : chars)
    {
        rectangle(color2, r, cv::Scalar(0, 255, 0), 1);
    }

    cv::imshow("small", color2);
    cv::waitKey(0);

    double val = double(1+chars.back().x - chars[0].x + chars.back().width) / chars.size();
    std::cout << "val is " << val << std::endl;
}
